package org.jeecg.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

public class PageUtils {
    /**
     * MyBatis-Plus page属性复制
     *
     * @param sourcePage the source page
     * @param clazz      class to instantiate
     * @return
     */
    public static <T> Page<T> copyProperties(Page<?> sourcePage, Class<T> clazz) {
        if (sourcePage == null) {
            return null;
        }

        Page<T> result = new Page<T>();
        result.setCurrent(sourcePage.getCurrent());
        result.setSize(sourcePage.getSize());
        result.setTotal(sourcePage.getTotal());
        result.setPages(sourcePage.getPages());
        result.setRecords(copyProperties(sourcePage.getRecords(), clazz));
        result.setSearchCount(sourcePage.searchCount());
        result.setOptimizeCountSql(sourcePage.optimizeCountSql());
        return result;
    }

    /**
     * list集合 属性复制
     *
     * @param sourceList the source list
     * @param clazz      class to instantiate
     * @param <T>
     * @return
     */
    public static <T> List<T> copyProperties(List<?> sourceList, Class<T> clazz) {
        if (sourceList == null) {
            return null;
        }
        return sourceList.stream().map(item -> copyProperties(item, clazz)).collect(Collectors.toList());
    }

    /**
     * 对象 属性复制
     *
     * @param source the source bean
     * @param clazz  class to instantiate
     * @param <T>
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        T result = null;
        try {
            result = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        BeanUtils.copyProperties(source, result);
        return result;
    }
}
